let body = document.body;
let head = document.head;
let youmulu = ["springboot-datasource-druid"];//需要加载右边的目录

let logaPath = '/file/logo.png';
let nodeArray = [
    //logo
    {tagName:'link', rel:'shortcut icon', type:'image/x-icon', href:logaPath},
    //docsify脚本
    {tagName:'link',rel:'stylesheet',href:'https://cdn.jsdelivr.net/npm/docsify/themes/vue.css'},
    {tagName:'script',src:'https://cdn.jsdelivr.net/npm/docsify/lib/docsify.js'},
    //emoji表情
    {tagName:'script', src:'//cdn.jsdelivr.net/npm/docsify/lib/plugins/emoji.min.js'},
    //不蒜子
    {tagName:'script',src:'//busuanzi.ibruce.info/busuanzi?jsonpCallback=BusuanziCallback',referrerPolicy:'no-referrer-when-downgrade'},
    //搜索插件
    {tagName:'script', src:'//cdn.staticfile.org/docsify/4.12.2/plugins/search.min.js'},
];

//通用配置
window.$docsify = {
    name: '澜澜爱学习',
    repo: '',
    loadSidebar: true, // 增加：自动加载侧边栏
    coverpage: true,//开启封面
    onlyCover: true,//封面就独立成封面
    loadNavbar: true,//导航栏嵌套
    auto2top:true,//切换界面是否跳转到顶部
    //小屏设备下合并导航栏到侧边栏
    mergeNavbar: true,
    //搜索插件
    search: {
        maxAge: 86400000,
        paths: 'auto',
        placeholder: '搜索',
        noData: '找不到结果',
        depth: 4,
        hideOtherSidebarContent: false,
        namespace: '澜澜爱学习'
    },
    busuanzi_value:{
        site_uv: -1,//uv的方式，单个用户连续点击n篇文章，只记录1次访客数
        page_pv: -1,//pv的方式，单个用户点击1篇文章，本篇文章记录1次阅读量
        site_pv: -1,//pv的方式，单个用户连续点击n篇文章，记录n次访问量
        version: 2.4
    },
    plugins: [
        //底部版权声明
        function(hook, vm) {
            hook.beforeEach(function(html) {
                return html +
                    "\n" +
                    "<br/>" +
                    "<br/>" +
                    "<hr>" +
                    //"<a target='_blank' href=''></a><br/>" +
                    //onclick="window.open('https://huanzi-qch.gitee.io/file-server/ad/adservice.html', '_blank')"
                    "<p><span style='color: #1e2a35;cursor: pointer; '  title=\"AD广告位服务说明\">AD广告位</span>（长期招租，如有需要请私信）</p>" +
                    //"<a target='_blank' href='https://www.jeata.com/?hmsr=promotion&hmpl=huanzi-qch'>XXX广告位</a><br/>" +
                    //"<br/>" +
                    //"<a target='_blank' href='https://www.aliyun.com/activity?userCode=ckkryd9h'>【阿里云】阿里云最全的优惠活动聚集地！</a><br/>" +
                    //"<a target='_blank' href='https://cloud.tencent.com/act/cps/redirect?redirect=11447&cps_key=e1c9db729edccd479fc902634492bf53'>【腾讯云】腾讯云当前最新优惠活动专区！</a><br/>" +
                    "<span style=''>© 2022 - 至今 lanlan-xgj</span>" +
                    "<br/>" +
                    "<span style=''>如转载请附上原文出处链接及本声明。</span>" +
                    "<span id='busuanzi_container_site_pv' style='float: right;'>本站总访问量 <span id='busuanzi_value_site_pv'>" + window.$docsify.busuanzi_value.site_pv + "</span> 次</span>" +
                    "<hr>";
            });
        },
        //返回顶部
        function(hook, vm) {
            let CONFIG = {
                auto: true,
                text: '顶部',
                right: 15,
                bottom: 140,
                offset: 500
            };
            let opts = vm.config.scrollToTop || CONFIG;
            CONFIG.auto = opts.auto && typeof opts.auto === "boolean" ? opts.auto : CONFIG.auto;
            CONFIG.text = opts.text && typeof opts.text === "string" ? opts.text : CONFIG.text;
            CONFIG.right = opts.right && typeof opts.right === "number" ? opts.right : CONFIG.right;
            CONFIG.bottom = opts.bottom && typeof opts.bottom === "number" ? opts.bottom : CONFIG.bottom;
            CONFIG.offset = opts.offset && typeof opts.offset === "number" ? opts.offset : CONFIG.offset;
            let onScroll = function(e) {
                if (!CONFIG.auto) {
                    return
                }
                let offset = window.document.documentElement.scrollTop;
                let $scrollBtn = Docsify.dom.find("span.scroll-to-top");
                $scrollBtn.style.display = offset >= CONFIG.offset ? "block" : "none"
            };
            hook.mounted(function() {
                let scrollBtn = document.createElement("span");
                scrollBtn.className = "scroll-to-top";
                scrollBtn.style.display = CONFIG.auto ? "none" : "block";
                scrollBtn.style.overflow = "hidden";
                scrollBtn.style.position = "fixed";
                scrollBtn.style.right = CONFIG.right + "px";
                scrollBtn.style.bottom = CONFIG.bottom + "px";
                scrollBtn.style.width = "50px";
                scrollBtn.style.height = "50px";
                scrollBtn.style.background = "white";
                scrollBtn.style.color = "#666";
                scrollBtn.style.border = "1px solid #ddd";
                scrollBtn.style.borderRadius = "4px";
                scrollBtn.style.lineHeight = "42px";
                scrollBtn.style.fontSize = "16px";
                scrollBtn.style.textAlign = "center";
                scrollBtn.style.boxShadow = "0px 0px 6px #eee";
                scrollBtn.style.cursor = "pointer";
                let textNode = document.createTextNode(CONFIG.text);
                scrollBtn.appendChild(textNode);
                document.body.appendChild(scrollBtn);
                window.addEventListener("scroll", onScroll);
                scrollBtn.onclick = function(e) {
                    e.stopPropagation();
                    let step = window.scrollY / 15;
                    let scroll = function() {
                        window.scrollTo(0, window.scrollY - step);
                        if (window.scrollY > 0) {
                            setTimeout(scroll, 15)
                        }
                    };
                    scroll()
                }
            })
        }
    ]
};

//不蒜子 页面访问统计回调
function BusuanziCallback(data){
    console.log(data);
    window.$docsify.busuanzi_value = data;
    document.getElementById('busuanzi_value_site_pv').innerText = window.$docsify.busuanzi_value.site_pv;
}

//更新自定义右侧目录，以及反防盗链
function update(url){
    //自动目录
    let catalogue = document.getElementsByClassName('catalogue');
    if(catalogue.length <= 0){
        catalogue = document.createElement('div');
        catalogue.className = 'catalogue';
        body.append(catalogue);
    }else{
        catalogue = catalogue[0];
        catalogue.innerHTML = "";
    }
    catalogue.style.display='none';

    setTimeout(function () {
        //img图片反防盗链
        for(let img of document.getElementsByTagName('img')){
            img.setAttribute('referrerPolicy','no-referrer');
        }

        //自动目录
        let close = document.createElement('a');
        close.className = 'catalogue-close';
        close.onclick = function (){
            this.parentElement.remove();
        }
        close.innerText = '✕';
        catalogue.append(close);
        for(let child of document.getElementById('main').children){
            if(child.nodeName === 'H2' || child.nodeName === 'H3'){
                let a = document.createElement('a');
                a.href = url + "?id=" + child.id;
                a.innerText = child.innerText;

                if(child.nodeName === 'H2'){
                    a.className = 'catalogue-h2';
                }else{
                    a.className = 'catalogue-h3';
                }
                catalogue.append(a);
            }
        }
        catalogue.style.display='block';
    },1000);
}


//是否包含
function isYoumulu(url){
    let youmuluIn = false;
    for (let i = 0; i < youmulu.length; i++){
        if(url.indexOf(youmulu[i]) !== -1) {//包含
            youmuluIn = true;
            break;
        }
    }
    return youmuluIn;
}

//DOM加载完成执行
(function (){
    //动态引入脚本
    for(let node of nodeArray){
        let element = document.createElement(node.tagName);
        for(let key in node){
            if('tagName' !== key){
                element[key] = node[key];
            }
        }
        if('link' === node.tagName){
            head.append(element);
        }else{
            body.append(element);
        }
    }

    //监听URL发生变化，是否生成自定义右侧目录
    let url = window.location.href;
    if(isYoumulu(url)){//包含
        url = window.location.hash.split("?")[0];
        update(url);
    }

    window.onhashchange = function () {
        let catalogue = document.getElementsByClassName('catalogue');
        let url2 = window.location.href;//当前点击地址
        let hash = window.location.hash.split("?")[0];//当前点击地址
        if(hash !== '#/' && url.indexOf(hash) === -1){
            if(catalogue.length > 0){
                catalogue[0].remove();
            }
            if(isYoumulu(url2)){//包含
                update(hash);
            }else {
                if(catalogue.length > 0){
                    catalogue[0].remove();
                }
            }
        }else{
            if(!isYoumulu(url2)){
                if(catalogue.length > 0){
                    catalogue[0].remove();
                }
            }
        }
        url = hash;//赋值给url当前点击地址
    };
})();